package me.stone.stanimeclient

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import me.stone.stanimeclient.core.common.extensions.throttle
import timber.log.Timber

fun interface IOnFanItemClicked {
    fun seeFanDetailItem(id: Int)
}

class MainViewModel: ViewModel(), IOnFanItemClicked {

    companion object {
        private const val THROTTLE_TIME = 500L
    }

    private val _seeFanDetail = MutableSharedFlow<Int>()
    val seeFanDetail: Flow<Int> = _seeFanDetail
        .filter { it > 0 }
        .throttle(THROTTLE_TIME)
        .shareIn(viewModelScope, SharingStarted.Eagerly)

    override fun seeFanDetailItem(id: Int) {
        Timber.d("see detail id: $id")
        viewModelScope.launch {
            _seeFanDetail.emit(id)
        }
    }

    private val _recommendQuery = MutableStateFlow("")
    val recommendQuery: StateFlow<String> = _recommendQuery

    fun updateRecommendQuery(query: String) {
        viewModelScope.launch {
            _recommendQuery.emit(query)
        }
    }

}